﻿/**
* 公共处理脚本
*/
(function (o) {

    /**
    * @description  ajax请求
    * @param {String} url
    * @param {Object} data
    * @param {Function} successCallback
    * @param {Function} errorCallback
    */
    o.ajax = function (url, data, successCallback, errorCallback) {
        data.r = Math.random();
        $.ajax({
            url: url,
            data: data,
            type: 'post',
            dataType: 'json',
            cache: false,
            async: true,
            success: function (result) {
                successCallback && successCallback(result);
            },
            error: function (xhr, status, error) {
                errorCallback && errorCallback(xhr);
            }
        });
    };

    /**
    * @description  ajax请求
    * @param {String} url
    * @param {Object} data
    * @param {Function} successCallback
    * @param {Function} errorCallback
    */
    o.list = function (url, data, successCallback, errorCallback) {
        data.PostType = 'list';
        o.ajax(url, data, successCallback, errorCallback);
    };

    /**
    * @description  get处理
    * @param {String} url
    * @param {Object} data
    * @param {Function} successCallback
    * @param {Function} errorCallback
    */
    o.get = function (url, data, successCallback, errorCallback) {
        data.PostType = 'get';
        o.ajax(url, data, successCallback, errorCallback);
    };

    /**
    * @description  set处理
    * @param {String} url
    * @param {Object} data
    * @param {Function} successCallback
    * @param {Function} errorCallback
    */
    o.set = function (url, data, successCallback, errorCallback) {
        data.PostType = 'set';
        o.ajax(url, data, successCallback, errorCallback);
    };

    /**
    * @desc  del处理
    * @param {String} url
    * @param {Object} data
    * @param {Function} successCallback
    * @param {Function} errorCallback
    */
    o.del = function (url, data, successCallback, errorCallback) {
        data.PostType = 'del';
        o.ajax(url, data, successCallback, errorCallback);
    };

    /**
    * @description  加载数据赋值
    * @param {String} url
    * @param {Object} data
    * @param {Function} successCallback
    * @param {Function} errorCallback
    */
    o.loadData = function (url, data, successCallback, errorCallback) {
        o.ajax(url, data, function (data) {
            if (data) {
                $("input[type='text']").each(function (i) {
                    var name = $(this).attr("id");
                    if (name != undefined && name != null && name != "" && name.indexOf("tb") == 0) {
                        name = name.substr(2, name.length)
                        if (data[name] != null && data[name] != "null") {
                            $(this).val(data[name]);
                        }
                    }
                });
                $("input[type='number']").each(function (i) {
                    var name = $(this).attr("id");
                    if (name != undefined && name != null && name != "" && name.indexOf("tb") == 0) {
                        name = name.substr(2, name.length)
                        if (data[name] != null && data[name] != "null") {
                            $(this).val(data[name]);
                        }
                    }
                });
                $("textarea").each(function (i) {
                    var name = $(this).attr("id");
                    if (name != undefined && name != null && name != "" && name.indexOf("tb") == 0) {
                        name = name.substr(2, name.length)
                        if (data[name] != null && data[name] != "null") {
                            $(this).text(data[name]);
                        }
                    }
                });
                $("label").each(function (i) {
                    var name = $(this).attr("id");
                    if (name != undefined && name != null && name != "" && name.indexOf("lbl") == 0) {
                        name = name.substr(3, name.length)
                        if (data[name] != null && data[name] != "null") {
                            $(this).text(data[name] == null ? "" : data[name]);
                        }
                    }
                });
            }
            successCallback && successCallback(data);
        }, function (err) {
            errorCallback && errorCallback(err);
        });
    };

    /*
    * @description  checkbox选中
    * @param {String} value
    * @param {Object} row
    * @param {Number} index
    */
    o.stateFormatter = function (value, row, index) {
        if (row.rowstate == "true") {
            return {
                disabled: true, //设置是否可用
                checked: true//设置选中
            };
        } else {
            return {
                checked: false//设置选中
            };
        }
        return "";
    };

    /**
    * @description  是否为空
    * @param {Object} value
    */
    o.isNull = function (value) {
        if (value == null || value == 'null' || value == '' || value == undefined || value == 'undefined') {
            return true;
        }
        return false;
    };

    /**
    * @description  设置为空
    * @param {Object} value
    */
    o.setEmpty = function (value) {
        if (value == null || value == 'null' || value == '' || value == undefined || value == 'undefined') {
            return '';
        }
        return value;
    };


    /**
    * @description  是否小数，保留几位
    * @param {Object} value num
    */
    o.isNum = function (value, num) {
        var regu = /^[0-9]+\.?[0-9]*$/;
        if (value != "") {
            if (regu.test(value)) {
                if (num == 0) {
                    if (value.indexOf('.') == -1) {
                        return true;
                    }
                }
                if (value.indexOf('.') > -1) {
                    if (value.split('.')[1].length <= num) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
    * @description  截取时间
    * @param {Object} value
    */
    o.getTDate = function (value) {
        if (value && value != null) {
            return value.substring(0, 19).replace("T", " ");
        }
        return "";
    };

    /**
    * @description  截取时间
    * @param {Object} value
    */
    o.getTDate2 = function (value) {
        if (value) {
            return value.split("T")[0];
        }
        return "";
    };

    /**
    * @description  截取时间
    * @param {Object} value
    */
    o.getTDate3 = function (value) {
        if (value) {
            return value.split(" ")[0];
        }
        return "";
    };

    /**
    * @description  格式化身份证 掩藏其中的六位
    * @param {Object} value
    */
    o.formatterIDCard = function (value) {
        if (value && value.length >= 15) {
            var ymd = value.substr(5, 10);
            return value.replace(ymd, '******')
        }
        return value;
    };

    /**
    * @description  打开新页面
    * @param {String} url //URL地址
    * @param {String} title //标题
    * @param {Boolean} isFull //是否最大化 
    */
    o.openLayer = function (url, title, isFull) {
        var config = {
            type: 2,
            title: title,
            shadeClose: true,
            content: url,
            closeBtn: 1,
            shade: 0,
            scrollbar: false,
            success: function () {
            },
            end: function () { }
        };
        if (isFull) {
            config.area = ['100%', '100%'];
        }
        var index = layer.open(config);
    };

    /**
    * @description  打开新页面
    * @param {String} url //URL地址
    * @param {String} width //页面宽
    * @param {String} height //页面高
    * @param {Boolean} isFull //是否最大化 
    */
    o.openDiyLayer = function (url, width, height, isFull) {
        var index = layer.open({
            type: 2,
            title: false,
            shadeClose: true,
            content: url,
            closeBtn: 1,
            area: [width, height],
            success: function () {
            },
            end: function () { }
        });
        if (isFull) {
            layer.full(index);
        }
    };

    /**
    * @description  打开新页面
    * @param {String} url //URL地址
    * @param {String} width //页面宽
    * @param {String} height //页面高
    * @param {Boolean} isFull //是否最大化 
    */
    o.openDiyLayer2 = function (url, title, width, height, isFull) {
        var index = layer.open({
            type: 2,
            title: title,
            shadeClose: false,
            content: url,
            closeBtn: 1,
            area: [width, height],
            success: function () {
            },
            end: function () { }
        });
        if (isFull) {
            layer.full(index);
        }
    };

    /**
    * @description  获取地址栏参数值
    * @param {String} variable //参数
    */
    o.getRequest = function (variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0].toLowerCase() == variable.toLowerCase()) { return pair[1]; }
        }
        return '';
    };

    /**
    * @description  当前月份
    */
    o.getNowMonth = function () {
        var date = new Date(); //得到当前日期原始模式
        var newyear = date.getFullYear(); //得到当前日期年份
        var newmonth = date.getMonth() + 1; //得到当前日期月份（注意： getMonth()方法一月为 0, 二月为 1, 以此类推。）
        newmonth = (newmonth < 10 ? "0" + newmonth : newmonth); //10月以下的月份自动加0 
        var newdate = newyear + "-" + newmonth;
        return newdate;
    }

    /**
    * @description  当前日期
    */
    o.getNowDate = function () {
        var date = new Date(); //得到当前日期原始模式
        var newyear = date.getFullYear(); //得到当前日期年份
        var newmonth = date.getMonth() + 1; //得到当前日期月份（注意： getMonth()方法一月为 0, 二月为 1, 以此类推。）
        var day = date.getDate(); //得到当前某日日期（1-31）
        newmonth = (newmonth < 10 ? "0" + newmonth : newmonth); //10月以下的月份自动加0 
        var newdate = newyear + "-" + newmonth + "-" + day;
        return newdate;
    }

    /**
    * @description  当前时间
    */
    o.getNowTime = function () {
        var now = new Date();
        var hour = now.getHours(); //得到小时
        var minu = now.getMinutes(); //得到分钟
        var sec = now.getSeconds(); //得到秒
        if (hour < 10) hour = "0" + hour;
        if (minu < 10) minu = "0" + minu;
        if (sec < 10) sec = "0" + sec;
        var time = hour + ":" + minu + ":" + sec;
        return time;
    }

    /**
    * @description  减时间
    * @param {String} type 类型 h\m\s
    * @param {Number} interval 间隔
    */
    o.getReduceTime = function (type, interval) {
        var now = new Date();
        var timestamp = null;
        switch (type) {
            case "h": timestamp = now.setHours(now.getHours() - interval); break;     //小时
            case "m": timestamp = now.setMinutes(now.getMinutes() - interval); break; //分钟
            case "s": timestamp = now.setSeconds(now.getSeconds() - interval); break; //秒
        }
        var newTime = new Date(timestamp);
        var hour = newTime.getHours();      //得到小时
        var minu = newTime.getMinutes();    //得到分钟
        var sec = newTime.getSeconds();     //得到秒
        if (hour < 10) hour = "0" + hour;
        if (minu < 10) minu = "0" + minu;
        if (sec < 10) sec = "0" + sec;
        var time = hour + ":" + minu + ":" + sec;
        return time;
    }

    /**
    * @description  加时间
    * @param {String} type 类型 h\m\s
    * @param {Number} interval 间隔
    */
    o.getPlusTime = function (type, interval) {
        var now = new Date();
        var timestamp = null;
        switch (type) {
            case "h": timestamp = now.setHours(now.getHours() + interval); break;     //小时
            case "m": timestamp = now.setMinutes(now.getMinutes() + interval); break; //分钟
            case "s": timestamp = now.setSeconds(now.getSeconds() + interval); break; //秒
        }
        var newTime = new Date(timestamp);
        var hour = newTime.getHours();      //得到小时
        var minu = newTime.getMinutes();    //得到分钟
        var sec = newTime.getSeconds();     //得到秒
        if (hour < 10) hour = "0" + hour;
        if (minu < 10) minu = "0" + minu;
        if (sec < 10) sec = "0" + sec;
        var time = hour + ":" + minu + ":" + sec;
        return time;
    }

    /** 
    * @description select元素动态添加option
    * @param selectEleId select元素id 
    * @param width 要添加的option的value属性值 
    * @param height 要添加的option的innerHTML 
    * @param selected 是否选中 
    */
    o.addOption = function (selectEleId, optionValue, optionInnerHTML, selected) {
        var selectEle = document.getElementById(selectEleId);
        var optionObj = document.createElement("option");
        optionObj.value = optionValue;
        optionObj.innerHTML = optionInnerHTML;
        optionObj.selected = selected;
        selectEle.appendChild(optionObj);
    }

    /**
    * @description 显示基础的操作按钮
    * @param {String} key 主键字段
    * @param {Object} row 当前行
    * @return {String} htmlstring
    */
    o.getOperationMenu = function (key, row) {
        var acthtml = '';
        var opHtml = $('#bst_tableEvent').html();
        if (opHtml) {
            var eventJson = $.parseJSON(opHtml);
            $.each(eventJson, function (idx, item) {
                acthtml += '<a class="btn-' + item.MenuEvent + '" onclick="' + item.MenuEvent + '(\'' + row[key] + '\')">' + item.MenuName + '</a>';
            });
        }
        return acthtml;
    };

    //var tableData = $("#table").bootstrapTable('getData');
    //var row = tableData[index];
    /**
    * @description 显示基础的操作按钮-多个参数传递索引再获取行数据
    * @param {String} key 主键字段
    * @param {Object} row 当前行
    * @return {String} htmlstring
    */
    o.getOperationMenuRowIndex = function (index) {
        var acthtml = '';
        var opHtml = $('#bst_tableEvent').html();
        if (opHtml) {
            var eventJson = $.parseJSON(opHtml);
            $.each(eventJson, function (idx, item) {
                acthtml += '<a class="btn-' + item.MenuEvent + '" onclick="' + item.MenuEvent + '(\'' + index + '\')">' + item.MenuName + '</a>';
            });
        }
        return acthtml;
    };

    /**
    * @description 初始化下拉框 
    * @param  {Object} o
    * url: ajax地址  elementID：select控件ID  keyField：主键字段 keyValue：主键值字段
    */
    o.initSelectData = function (option, callback) {
        $.ajax({
            url: option.url,
            type: 'post',
            dataType: 'json',
            cache: false,
            async: false,
            success: function (data) {
                if (data && data.rows) {
                    o.addOption(option.elementID, '', '--请选择--', false);
                    $.each(data.rows, function (index, item) {
                        o.addOption(option.elementID, item[option.keyField], item[option.keyValue], false);
                    });
                }
                layui.form.render('select');

                callback && callback(data);
            }
        });
    };

    /**
    * 获取上传附件
    */
    o.getFileJson = function (o) {
        var json = "[";
        $(o).each(function () {
            json += "{";
            json += "\"AnnexName\":" + "\"" + $(this).attr('annexname') + "\",";
            json += "\"AnnexPath\":" + "\"" + $(this).attr('annexpath') + "\",";
            json += "\"AnnexSize\":" + "\"" + $(this).attr('annexsize') + "\",";
            json += "\"FilePath\":" + "\"" + $(this).attr('filepath') + "\"";
            json += "},";
        });
        if (json.indexOf(',') > 0) {
            json = json.substring(0, json.length - 1);
        }
        json += "]";
        return json;
    };

    /**
    * 抛出一个异常错误信息
    * @param {String} msg
    */
    o.throwError = function (msg) {
        throw new Error(msg);
        return;
    };
    /**
    * 弹出一个错误提示
    * @param {String} msg
    */
    o.msgError = function (msg) {
        layer.msg(msg, {
            icon: 5
        });
        return;
    };
    /**
    * 弹出一个成功提示
    * @param {String} msg
    */
    o.msgSuccess = function (msg) {
        layer.msg(msg, {
            icon: 1
        });
        return;
    };

    /**
    * 键盘事件
    */
    o.onKeyDown = function (event) {
        if ((event.keyCode || event.which) == 13) {
            event.preventDefault() || (event.returnValue = false);
            search && search();
        }
    };

    o.backToMain = function () {
        top.layer.closeAll();
    }

}(window.app = {}));


//jquery扩展
$.fn.extend({
    insertContent: function (myValue, t) {
        var $t = $(this)[0];
        if (document.selection) {
            this.focus();
            var sel = document.selection.createRange();
            sel.text = myValue;
            this.focus();
            sel.moveStart('character', -l);
            var wee = sel.text.length;
            if (arguments.length == 2) {
                var l = $t.value.length;
                sel.moveEnd("character", wee + t);
                t <= 0 ? sel.moveStart("character", wee - 2 * t - myValue.length) : sel.moveStart("character", wee - t - myValue.length);
                sel.select();
            }
        } else if ($t.selectionStart || $t.selectionStart == '0') {
            var startPos = $t.selectionStart;
            var endPos = $t.selectionEnd;
            var scrollTop = $t.scrollTop;
            $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
            this.focus();
            $t.selectionStart = startPos + myValue.length;
            $t.selectionEnd = startPos + myValue.length;
            $t.scrollTop = scrollTop;
            if (arguments.length == 2) {
                $t.setSelectionRange(startPos - t, $t.selectionEnd + t);
                this.focus();
            }
        } else {
            this.value += myValue;
            this.focus();
        }
    }
});


//以下为平台验证通用
//身份证验证开始
var aCity = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外" };

function isCardID(sId) {
    var iSum = 0;
    var info = "";
    if (!/^\d{17}(\d|x)$/i.test(sId)) return false;

    sId = sId.replace(/x$/i, "a");
    if (aCity[parseInt(sId.substr(0, 2))] == null) return false;

    var sBirthday = sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2));
    var d = new Date(sBirthday.replace(/-/g, "/"));
    if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate())) return false;

    for (var i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
    if (iSum % 11 != 1) return false;

    return true; //aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女")   
}
//身份证验证结束

//邮箱验证开始
function isEmail(code) {
    var pattern = /\w@\w*\.\w/;
    if (code != "") {
        return pattern.test(code);
    }
    return false;
}
//邮箱验证结束


//邮编验证开始
function isPostcode(code) {
    var pattern = /^[1-9][0-9]{5}$/;
    if (code != "") {
        return pattern.test(code);
    }
    return false;
}
//邮编验证结束

//数字验证
function IsNumber(chkvalue) {
    if (chkvalue.length == 0)
        return true;
    if (isNaN(chkvalue) || chkvalue < 0) {
        return false;
    }
    return true;
}
//带四位小数
function IsNumber4(numvalue) {
    if (IsNumber(numvalue)) {
        var num = numvalue.split('.');
        if (num[1] && num[1].length > 4) {
            return false;
        }
        return true;
    }
    return false;
}
//带两位小数
function IsNumber2(numvalue) {
    if (IsNumber(numvalue)) {
        var num = numvalue.split('.');
        if (num[1] && num[1].length > 2) {
            return false;
        }
        return true;
    }
    return false;
}
//带一位小数
function IsNumberh(numvalue) {
    if (IsNumber(numvalue)) {
        var num = numvalue.split('.');
        if (num[1] && num[1].length > 1) {
            return false;
        }
        return true;
    }
    return false;
}

//复杂密码校验
function IsComplexPwd(pwd) {
    //密码必须大于8位且要包含大小写字母、数字
    var reg = /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(.{8,})$/;
    if (reg.test(pwd)) {
        return true;
    }
    return false;
}

//layui的验证扩展
setTimeout(function () {
    if ($('form').hasClass("layui-form")) {
        layui.use('form', function () {
            var form = layui.form;
            //自定义验证 自带验证非必填为空值也会验证，所有要重新自定义验证
            form.verify({
                mobile: function (value) {
                    if (value) {
                        var reg = /^1[3|4|5|6|7|8|9]\d{9}$/;
                        if (!reg.test(value)) {
                            return "手机号码格式不正确";
                        }
                    }
                },
                digital: function (value) {
                    if (value) {
                        var reg = /^[0-9]*$/;
                        if (!reg.test(value)) {
                            return "请输入非负数";
                        }
                    }
                },
                idcard: function (value) {
                    if (value) {
                        if (!isCardID(value)) {
                            return "身份证格式不正确";
                        }
                    }
                },
                postcode: function (value) {
                    if (value) {
                        if (!isPostcode(value)) {
                            return "邮编格式不正确";
                        }
                    }
                },
                email: function (value) {
                    if (value) {
                        if (!isEmail(value)) {
                            return "邮箱地址不正确";
                        }
                    }
                },
                number: function (value) {
                    if (value) {
                        var reg = /^\d+$/;
                        if (!reg.test(value)) {
                            return "必须为数字";
                        }
                    }
                },
                decimal: function (value) {
                    if (value) {
                        if (!IsNumber(value)) {
                            return "必须为数字";
                        }
                    }
                },
                ndecimalh: function (value) {
                    if (value) {
                        if (!IsNumberh(value)) {
                            return "只能输入带一位小数的值";
                        }
                    }
                },
                ndecimal: function (value) {
                    if (value) {
                        if (!IsNumber2(value)) {
                            return "只能输入带两位小数的值";
                        }
                    }
                },
                ndecimal4: function (value) {
                    if (value) {
                        if (!IsNumber4(value)) {
                            return "只能输入带四位小数的值";
                        }
                    }
                },
                isCoordinate: function (value) {
                    if (value) {
                        if (value.indexOf(',') > 0) {
                            var lng = value.split(',')[0]; //经度
                            var lat = value.split(',')[1]; //纬度
                            if (!IsNumber(lng) || !IsNumber(lat)) {
                                return "坐标格式不正确";
                            }
                        } else {
                            return "坐标格式不正确";
                        }
                    }
                },
                IP: function (value) {
                    if (value) {
                        var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
                        if (!reg.test(value)) {
                            return "IP格式不正确";
                        }
                    }
                },
                length100: function (value) {
                    if (value && value.length > 100) {
                        return "字符长度超过100";
                    }
                },
                length50: function (value) {
                    if (value && value.length > 50) {
                        return "字符长度超过50";
                    }
                },
                length25: function (value) {
                    if (value && value.length > 25) {
                        return "字符长度超过25";
                    }
                },
                length150: function (value) {
                    if (value && value.length > 150) {
                        return "字符长度超过150";
                    }
                },
                length250: function (value) {
                    if (value && value.length > 250) {
                        return "字符长度超过250";
                    }
                },
                length5: function (value) {
                    if (value && value.length > 5) {
                        return "字符长度超过5";
                    }
                },
                length8: function (value) {
                    if (value && value.length > 8) {
                        return "字符长度超过8";
                    }
                },
                length10: function (value) {
                    if (value && value.length > 10) {
                        return "字符长度超过10";
                    }
                },
                length18: function (value) {
                    if (value && value.length > 18) {
                        return "字符长度超过18";
                    }
                }
            });
        });
    }
}, 50);